// 浏览足迹页面
Page({
  data: {
    // 按日期分组的浏览记录
    historyGroups: [],
    // 刷新状态
    refreshing: false,
    // 是否还有更多数据
    hasMore: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('浏览足迹页面加载');
    this.loadBrowseHistory();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 页面显示时刷新浏览记录
    this.loadBrowseHistory();
  },

  /**
   * 加载浏览记录
   */
  loadBrowseHistory: function() {
    try {
      // 从本地存储获取浏览记录
      const browseHistory = wx.getStorageSync('browseHistory') || [];
      
      if (browseHistory.length === 0) {
        // 如果没有浏览记录，创建一些模拟数据用于演示
        const mockHistory = this.createMockHistory();
        this.setData({
          historyGroups: mockHistory
        });
        return;
      }
      
      // 按日期分组处理浏览记录
      const groupedHistory = this.groupHistoryByDate(browseHistory);
      
      this.setData({
        historyGroups: groupedHistory
      });
    } catch (error) {
      console.error('获取浏览记录失败:', error);
      // 出错时显示模拟数据
      const mockHistory = this.createMockHistory();
      this.setData({
        historyGroups: mockHistory
      });
    }
  },

  /**
   * 创建模拟浏览记录数据
   */
  createMockHistory: function() {
    return [
      {
        date: '2025-09-11',
        cars: [
          {
            id: 1,
            name: '红旗H9 2.0T旗畅版',
            subtitle: '2022款',
            year: '2022年',
            mileage: '1.27万公里',
            location: '64户',
            price: '26.18',
            downPayment: '首付5.68万',
            image: 'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=400&h=300&fit=crop',
            isNew: true,
            isHot: true,
            browseTime: '2025-09-11 15:30:00'
          },
          {
            id: 2,
            name: '奔驰C260L 运动版',
            subtitle: '2022款',
            year: '2022年',
            mileage: '1.27万公里',
            location: '64户',
            price: '32.50',
            downPayment: '首付6.80万',
            image: 'https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=400&h=300&fit=crop',
            isNew: true,
            isHot: true,
            browseTime: '2025-09-11 14:20:00'
          },
          {
            id: 3,
            name: '宝马3系 320Li M运动套装',
            subtitle: '2023款',
            year: '2023年',
            mileage: '0.85万公里',
            location: '64户',
            price: '28.90',
            downPayment: '首付5.95万',
            image: 'https://images.unsplash.com/photo-1503376780353-7e6692767b70?w=400&h=300&fit=crop',
            isNew: true,
            isHot: false,
            browseTime: '2025-09-11 13:15:00'
          }
        ]
      },
      {
        date: '2025-09-10',
        cars: [
          {
            id: 4,
            name: '奥迪A4L 40 TFSI 时尚动感型',
            subtitle: '2022款',
            year: '2022年',
            mileage: '2.15万公里',
            location: '64户',
            price: '25.80',
            downPayment: '首付5.20万',
            image: 'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=400&h=300&fit=crop',
            isNew: false,
            isHot: true,
            browseTime: '2025-09-10 16:45:00'
          },
          {
            id: 5,
            name: '特斯拉Model 3 后轮驱动版',
            subtitle: '2023款',
            year: '2023年',
            mileage: '0.95万公里',
            location: '64户',
            price: '22.99',
            downPayment: '首付4.80万',
            image: 'https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=400&h=300&fit=crop',
            isNew: false,
            isHot: true,
            browseTime: '2025-09-10 15:30:00'
          },
          {
            id: 6,
            name: '比亚迪汉EV 尊贵型',
            subtitle: '2022款',
            year: '2022年',
            mileage: '1.58万公里',
            location: '64户',
            price: '21.50',
            downPayment: '首付4.30万',
            image: 'https://images.unsplash.com/photo-1503376780353-7e6692767b70?w=400&h=300&fit=crop',
            isNew: false,
            isHot: false,
            browseTime: '2025-09-10 14:15:00'
          }
        ]
      },
      {
        date: '2025-09-09',
        cars: [
          {
            id: 7,
            name: '小鹏P7 后驱超长续航智享版',
            subtitle: '2021款',
            year: '2021年',
            mileage: '3.20万公里',
            location: '64户',
            price: '18.80',
            downPayment: '首付3.75万',
            image: 'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=400&h=300&fit=crop',
            isNew: false,
            isHot: false,
            browseTime: '2025-09-09 17:20:00'
          },
          {
            id: 8,
            name: '理想ONE 增程式',
            subtitle: '2021款',
            year: '2021年',
            mileage: '2.88万公里',
            location: '64户',
            price: '24.50',
            downPayment: '首付4.90万',
            image: 'https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=400&h=300&fit=crop',
            isNew: false,
            isHot: true,
            browseTime: '2025-09-09 16:10:00'
          },
          {
            id: 9,
            name: '蔚来ET5 75kWh',
            subtitle: '2022款',
            year: '2022年',
            mileage: '1.45万公里',
            location: '64户',
            price: '27.80',
            downPayment: '首付5.55万',
            image: 'https://images.unsplash.com/photo-1503376780353-7e6692767b70?w=400&h=300&fit=crop',
            isNew: false,
            isHot: true,
            browseTime: '2025-09-09 15:05:00'
          }
        ]
      },
      {
        date: '2025-09-08',
        cars: [
          {
            id: 10,
            name: '凯迪拉克CT5 28T 铂金运动型',
            subtitle: '2022款',
            year: '2022年',
            mileage: '1.98万公里',
            location: '64户',
            price: '23.80',
            downPayment: '首付4.75万',
            image: 'https://images.unsplash.com/photo-1549317661-bd32c8ce0db2?w=400&h=300&fit=crop',
            isNew: false,
            isHot: false,
            browseTime: '2025-09-08 18:30:00'
          },
          {
            id: 11,
            name: '雷克萨斯ES 200 卓越版',
            subtitle: '2021款',
            year: '2021年',
            mileage: '2.65万公里',
            location: '64户',
            price: '26.90',
            downPayment: '首付5.35万',
            image: 'https://images.unsplash.com/photo-1552519507-da3b142c6e3d?w=400&h=300&fit=crop',
            isNew: false,
            isHot: true,
            browseTime: '2025-09-08 17:15:00'
          }
        ]
      }
    ];
  },

  /**
   * 按日期分组浏览记录
   */
  groupHistoryByDate: function(historyList) {
    const groups = {};
    
    historyList.forEach(item => {
      const date = item.browseTime.split(' ')[0]; // 提取日期部分
      
      if (!groups[date]) {
        groups[date] = {
          date: date,
          cars: []
        };
      }
      
      groups[date].cars.push(item);
    });
    
    // 转换为数组并按日期倒序排列
    const groupArray = Object.values(groups);
    groupArray.sort((a, b) => new Date(b.date) - new Date(a.date));
    
    // 每个日期内的车辆按浏览时间倒序排列
    groupArray.forEach(group => {
      group.cars.sort((a, b) => new Date(b.browseTime) - new Date(a.browseTime));
    });
    
    return groupArray;
  },

  /**
   * 返回上一页
   */
  goBack: function() {
    wx.navigateBack({
      delta: 1
    });
  },

  /**
   * 查看车辆详情
   */
  viewCarDetail: function(e) {
    const car = e.currentTarget.dataset.car;
    console.log('查看车辆详情：', car);
    
    // 跳转到车辆详情页面
    wx.navigateTo({
      url: `/pages/car-detail/car-detail?id=${car.id}`
    });
  },

  /**
   * 添加浏览记录（供其他页面调用）
   */
  addBrowseRecord: function(carInfo) {
    try {
      let browseHistory = wx.getStorageSync('browseHistory') || [];
      
      // 检查是否已经存在该车辆的浏览记录
      const existIndex = browseHistory.findIndex(item => item.id === carInfo.id);
      
      // 添加浏览时间
      const recordWithTime = {
        ...carInfo,
        browseTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
      };
      
      if (existIndex !== -1) {
        // 如果存在，更新浏览时间并移到最前面
        browseHistory.splice(existIndex, 1);
      }
      
      // 添加到数组开头
      browseHistory.unshift(recordWithTime);
      
      // 限制浏览记录数量，保留最近100条
      if (browseHistory.length > 100) {
        browseHistory = browseHistory.slice(0, 100);
      }
      
      // 保存到本地存储
      wx.setStorageSync('browseHistory', browseHistory);
      
    } catch (error) {
      console.error('保存浏览记录失败:', error);
    }
  },

  /**
   * 下拉刷新
   */
  onRefresh: function() {
    console.log('下拉刷新浏览记录');
    this.setData({
      refreshing: true
    });
    
    // 模拟刷新延迟
    setTimeout(() => {
      this.loadBrowseHistory();
      this.setData({
        refreshing: false
      });
      wx.showToast({
        title: '刷新完成',
        icon: 'success',
        duration: 1000
      });
    }, 1000);
  },

  /**
   * 滚动到底部
   */
  onScrollToLower: function() {
    console.log('滚动到底部，可以加载更多内容');
    if (!this.data.hasMore) {
      wx.showToast({
        title: '没有更多了',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    
    // 这里可以加载更多历史记录
    // 目前使用模拟数据，所以设置为没有更多
    this.setData({
      hasMore: false
    });
  },

  /**
   * 清空浏览记录
   */
  clearHistory: function() {
    wx.showModal({
      title: '清空浏览记录',
      content: '确定要清空所有浏览记录吗？',
      success: (res) => {
        if (res.confirm) {
          try {
            wx.removeStorageSync('browseHistory');
            this.setData({
              historyGroups: []
            });
            wx.showToast({
              title: '已清空',
              icon: 'success'
            });
          } catch (error) {
            console.error('清空浏览记录失败:', error);
            wx.showToast({
              title: '清空失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  /**
   * 分享功能
   */
  onShareAppMessage: function () {
    return {
      title: '我的浏览足迹',
      path: '/pages/browse-history/browse-history'
    };
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline: function () {
    return {
      title: '我的浏览足迹'
    };
  }
});
